package main

import (
	"fmt"
	"io"
	"os"
)

type CountWriter struct {
	Writer io.Writer
	Count  int64
}

func (cw *CountWriter) Write(p []byte) (int, error) {
	fmt.Println("Write")
	n, err := cw.Writer.Write(p)
	if err != nil {
		return n, err
	}
	cw.Count += int64(n)
	// fmt.Printf("%d %d", n, cw.Count)
	return n, nil
}

// io.Writer 封装到 CountWriter中
// 调用CountWriter时，进行计数
func CountingWriter(w io.Writer) (io.Writer, *int64) {
	// var cw CountWriter
	// cw.Writer = w
	fmt.Println("CountingWriter")
	cw := CountWriter{
		Writer: w,
	}
	// 因为Write是*cw的方法，所以是*cw实现了io.Writer接口，*cw可以作为io.Writer类型
	return &cw, &cw.Count
}

func main() {
	cw, counter := CountingWriter(os.Stdout)
	fmt.Fprintf(cw, "%s", "Print something to the screen...")
	fmt.Println(*counter)
	// cw.Write([]byte("Append some"))
	// fmt.Println(*counter)
}
